<!-- 调拨单-详情 -->
<template>
	<view class="content">
		<!-- 顶部导航栏 -->
		<u-navbar :fixed="false" :title="titleName" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff">
			<view slot="right" @click="openScan">
				<uni-icons v-if="!$utils.isPda()" type="scan" size="24" color="#fff"></uni-icons>
			</view>
		</u-navbar>

		<!-- 表头信息 -->
		<view class="headTabWrap">
			<uni-segmented-control :current="currenTabIndex" :values="items" style-type="text" active-color="#51d0d0"
				@clickItem="onClickItem" />
			<view class="panelBtn" @click="togglePanel()">
				<uni-icons v-if="currenTabIndex==null" type="eye" size="24" color="#51D0D0"></uni-icons>
				<uni-icons v-else type="eye-slash" size="24" color="#8A8A8A"></uni-icons>
			</view>
		</view>

		<view class="headTabContent">
			<view v-show="currenTabIndex === 0">
				<u--form labelPosition="left" :model="formData" labelWidth="80">
					<u-form-item prop="FCode" borderBottom>
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform"
								color="#808080">{{$utils.toUniCode('&#xed1c;')}}</uni-icons>
							<text class="label-text">单据编号</text>
						</view>
						<u--input :value="formData.FCode" disabled disabledColor="#fff" placeholder="自动生成"
							border="none"></u--input>
					</u-form-item>
					<u-form-item prop="FDate" borderBottom>
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform"
								color="#808080">{{$utils.toUniCode('&#xe7ac;')}}</uni-icons>
							<text class="label-text">单据日期</text>
						</view>
						<u--input :value="formData.FDate" disabled disabledColor="#fff" border="none"
							placeholder="单据日期"></u--input>
					</u-form-item>
					<u-form-item prop="Comment" borderBottom>
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform"
								color="#808080">{{$utils.toUniCode('&#xec07;')}}</uni-icons>
							<text class="label-text">备注</text>
						</view>
						<u--input v-model="formData.Comment" placeholder="请输入" border="none"></u--input>
					</u-form-item>
				</u--form>
			</view>
			<view v-show="currenTabIndex === 1">
				<u--form labelPosition="left" :model="formData" labelWidth="80" class="form1">
					<u-form-item prop="FCKWarehouseName" borderBottom @click="openBaseScreen('限定出库仓库')">
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform"
								color="#808080">{{$utils.toUniCode('&#xe689;')}}</uni-icons>
							<text class="label-text">限定出库仓库</text>
						</view>
						<u-input :value="formData.FCKWarehouseName" disabled disabledColor="#fff"
							placeholder="请选择限定出库仓库" border="none">
							<template slot="suffix">
								<view @click.stop="clearformData('限定出库仓库')" v-if="formData.FCKWarehouseName">
									<u-icon name="close-circle"></u-icon>
								</view>
							</template>
						</u-input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item prop="FRKWarehouseName" borderBottom @click="openBaseScreen('入库仓库')">
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform"
								color="#808080">{{$utils.toUniCode('&#xe68d;')}}</uni-icons>
							<text class="label-text">入库仓库</text>
						</view>
						<u-input :value="formData.FRKWarehouseName" disabled disabledColor="#fff" placeholder="请选择入库仓库"
							border="none">
							<template slot="suffix">
								<view @click.stop="clearformData('入库仓库')" v-if="formData.FRKWarehouseName">
									<u-icon name="close-circle"></u-icon>
								</view>
							</template>
						</u-input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item prop="FRKStorageCode" borderBottom @click="openBaseScreen('入库库位')">
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform"
								color="#808080">{{$utils.toUniCode('&#xeb44;')}}</uni-icons>
							<text class="label-text">入库库位</text>
						</view>
						<u-input :value="formData.FRKStorageCode" disabled disabledColor="#fff" placeholder="请选择入库库位"
							border="none">
							<template slot="suffix">
								<view @click.stop="clearformData('入库库位')" v-if="formData.FRKStorageCode">
									<u-icon name="close-circle"></u-icon>
								</view>
							</template>
						</u-input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
				</u--form>
			</view>
		</view>

		<!-- 子表信息 -->
		<view class="detail">
			<!-- 子表页签 -->
			<view class="detail-label">
				<view>调拨明细</view>
			</view>

			<!-- 入库明细 -->
			<view>
				<u-empty v-show="!formDetail.length" icon="/static/image/Img/DataEmpty.png" :style="{height:srvHeight}"
					text="暂无调拨明细"></u-empty>
				<scroll-view v-show="formDetail.length" class="rowContainer" :style="{height:srvHeight}"
					:scroll-y="true" :scroll-with-animation="true" :scroll-into-view="'section'+scanRow">
					<view :id="'section'+index" class="productRow" :class="scanRow==index ? 'b-p' : 'b-p-t'"
						v-for="(row,index) in formDetail" @click="setScanRow(index)">
						<view class="productRow-title">
							<view style="flex: 1;">【{{index+1}}】{{row.ProductName}}
								<text style="margin-left: 5px;color: #c0392b;" class="isEdit"
									@click.stop="ViewInventory(row,index)">查看库存</text>
							</view>
							<view v-if="!formData.Approve" @click.stop="deleteRow(row,index)">
								<uni-icons fontFamily="CustomFontPlatform" :size="20"
									color="#c0392b">{{$utils.toUniCode('&#xead4;')}}</uni-icons>
							</view>
						</view>
						<view class="productRow-main">
							<view class="total-wrap">
								<text class="total-label">
									账面库存:
								</text>
								<text class="total-value">
									{{row.InventoryQty}}
								</text>
							</view>
							<view class="total-wrap">
								<text class="total-label">
									库存单位:
								</text>
								<text class="total-value">
									{{row.UnitName}}
								</text>
							</view>
						</view>
						<view class="productRow-main">
							<view class="total-wrap">
								<text class="total-label">
									扫码合计:
								</text>
								<text class="total-value">
									{{row.scannedQty}}
								</text>
							</view>
						</view>
						<view class="productRow-main">
							<text v-if="!formData.Approve" class="del-title">删除</text>
							<text class="batch-title">调出仓库</text>
							<text class="pos-title">调出库位</text>
							<text class="batch-title">调入仓库</text>
							<text class="pos-title">调入库位</text>
						</view>
						<view class="productRow-subWrap" v-for="(item,itemIndex) in row.batchCodeArray">
							<view class="productRow-sub">
								<view v-if="!formData.Approve" @click.stop="deleteCode(row, item, index, itemIndex)"
									class="del-content">
									<uni-icons fontFamily="CustomFontPlatform" :size="16"
										color="#c0392b">{{$utils.toUniCode('&#xeaaa;')}}</uni-icons>
								</view>
								<view class="batch-content">{{item.FCKWarehouseName}}</view>
								<view class="pos-content">
									{{item.posname}}
								</view>
								<view class="batch-content">{{item.FRKWarehouseName}}</view>
								<view class="pos-content" @click.stop="changePosition(index,itemIndex)">
									<text :class="[!formData.Approve ? 'isEdit' : '']">{{item.posname2}}</text>
								</view>
							</view>
							<view class="productRow-main">
								<view class="total-wrap">
									<text class="total-label">
										批次:
									</text>
									<text class="total-value">
										{{item.batch}}
									</text>
								</view>
								<view class="total-wrap">
									<text class="total-label">
										调拨数量:
									</text>
									<text class="total-value">
										<view class="qty-content" @click.stop="showChange(row,index,item,itemIndex)">
											<text :class="[!formData.Approve ? 'isEdit' : '']">{{item.qty}}</text>
										</view>
									</text>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom" :style="$utils.disposeSafeBottomFun()">
			<u-button v-if="!formData.Approve" size="small" color="#51d0d0" :disabled="ifConfirm" :loading="ifConfirm"
				@click="confirmSubmit">保存单据</u-button>
			<u-button v-if="!formData.Approve && formData.FStockID" size="small" color="#c0392b" :disabled="ifConfirm"
				:loading="ifConfirm" @click="confirmApprove">审核</u-button>
			<u-button v-if="formData.Approve" size="small" color="#c0392b" :disabled="ifConfirm" :loading="ifConfirm"
				@click="approveFunction">取消审核</u-button>
		</view>

		<!-- 子表数值修改弹窗 -->
		<u-modal :show="showChangePanel" :showCancelButton="true" :closeOnClickOverlay="true" confirmColor="#51d0d0"
			:duration="0" title="数量修改" @confirm="confirmChange" @cancel="cancelChange" @close="closeChange">
			<!-- <u--input ref="input" type="digit" v-model="newValue" focus fontSize="20px" color="#666666" border="none"
				clearable placeholder="请输入修改数量"></u--input> -->
			<!-- 适配低性能设备输入框 -->
			<input ref="input" type="digit" v-model="newValue" focus fontSize="20px" color="#666666" border="none"
				clearable placeholder="请输入修改数量"></input>
		</u-modal>


		<!-- 控制弹窗显示 -->
		<uni-popup ref="popupRef" type="bottom" :is-mask-click="false">
			<view class="popup-container">
				<view class="popup-title">选择库位批次库存</view>
				<uni-segmented-control :current="PopupTabIndex" :values="PopupItems" style-type="button"
					active-color="#51d0d0" @clickItem="onClickPopupItem" />
				<u-empty v-if="!getCurPosInvList(PopupTabIndex).length" icon="/static/image/Img/DataEmpty.png"
					:style="{height:'auto'}" text="暂无记录"></u-empty>
				<scroll-view v-if="getCurPosInvList(PopupTabIndex).length" scroll-y class="popup-scroll">
					<view v-for="(item, index) in getCurPosInvList(PopupTabIndex)" :key="index"
						:class="['record-block',item.inputQty>0 ? 'record-block-changed' : '']">

						<view class="record-row">
							<view class="record-item">
								<text class="record-item-label">物料编码：</text>
								<text class="record-item-value">{{ item.ProductCode }}</text>
							</view>
							<view class="record-item">
								<text class="record-item-label">物料批号：</text>
								<text class="record-item-value">{{ item.FBatchNo }}</text>
							</view>
						</view>

						<view class="record-row">
							<view class="record-item" @click.stop="changeInvPosition_CK(index,'弹窗出库仓库')">
								<text class="record-item-label">出库仓库：</text>
								<text v-if="item.FCKWarehouseName" class="record-item-value"
									:class="[PopupTabIndex == 2 ? 'isEdit' : '']">{{ item.FCKWarehouseName }}</text>
								<text v-if="!item.FCKWarehouseName && PopupTabIndex==2 " class="record-item-value"
									style="color: #0000FF;">请选择</text>
							</view>
							<view class="record-item" @click.stop="changeInvPosition_CK(index,'弹窗出库库位')">
								<text class="record-item-label">出库库位：</text>
								<text v-if="item.FCKStorageCode" class="record-item-value"
									:class="[PopupTabIndex == 2 ? 'isEdit' : '']">{{ item.FCKStorageCode }}</text>
								<text v-if="!item.FCKStorageCode && PopupTabIndex==2 " class="record-item-value"
									style="color: #0000FF;">请选择</text>
							</view>
						</view>

						<view class="record-row">
							<view class="record-item" v-if="PopupTabIndex!=2">
								<text class="record-item-label">账面库存：</text>
								<text class="record-item-value">{{ item.FQty }}</text>
							</view>
							<view class="record-item">
								<text class="record-item-label">库存单位：</text>
								<text class="record-item-value">{{ item.UnitName }}</text>
							</view>
						</view>

						<view class="record-row">
							<view class="record-item" @click.stop="changeInvPosition_RK(index,'弹窗入库仓库')">
								<text class="record-item-label">入库仓库：</text>
								<text v-if="item.FRKWarehouseName"
									class="record-item-value isEdit">{{ item.FRKWarehouseName }}</text>
								<text v-else class="record-item-value" style="color: #0000FF;">请选择</text>
							</view>
							<view class="record-item" @click.stop="changeInvPosition_RK(index,'弹窗入库库位')">
								<text class="record-item-label">入库库位：</text>
								<text v-if="item.FRKStorageCode"
									class="record-item-value isEdit">{{ item.FRKStorageCode }}</text>
								<text v-else class="record-item-value" style="color: #0000FF;">请选择</text>
							</view>
						</view>

						<view class="record-row">
							<view class="record-item">
								<text class="record-item-label">出库数量：</text>

								<input style="color: #0000FF;" v-model="item.inputQty" type="digit"
									placeholder="请输入出库数量" :custom-style="{
																	border: 'none',
																	borderBottom: '1px solid #ccc',
																	padding: '0'
																  }" input-align="left" @blur="() => validateItem(item)">
								<u-button v-if="PopupTabIndex!=2" @click="put_Qty(item)" text="默认带入" type="primary"
									size="mini"></u-button>
								</input>
							</view>
						</view>
					</view>
				</scroll-view>

				<view class="popup-footer">
					<button class="btn btn-default" @click="cancelInvSel">关闭</button>
					<button class="btn btn-primary" @click="confirmInvSel">确认</button>
				</view>
			</view>
		</uni-popup>


		<!-- PDA扫码 -->
		<m-pda-scancode v-if="$utils.isPda()" listenName="BatchEditScan"
			:SetContent="{action:$store.state.systemConfig.sysDeviceInfo.broadcastAction,extra:$store.state.systemConfig.sysDeviceInfo.broadcastResult}"></m-pda-scancode>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				titleName: '',
				currenTabIndex: 0, // 表头tab当前index
				items: ['基本项', '扫码项'], //	表头tab名称
				scanDisabled: false,
				ifConfirm: false,
				showChangePanel: false,
				scanRow: 0, // 当前扫码行
				headTabWrapHeight: 0, //	表头tab容器高度
				headTabContentHeight: 0, //	表头tab内容高度
				detailLabelHeight: 0, // 切换标签高度
				bottomHeight: 0, // 底部按钮高度
				srvHeight: 'auto', // scrollview高度
				oldValue: '',
				newValue: '',
				posRow: 0,
				posIdx: 0,
				formData: {
					FStockID: 0,
					FCode: '',
					FDate: '',
					FCKWarehouseID: 0,
					FCKWarehouseName: '',
					FRKWarehouseID: 0,
					FRKWarehouseName: '',
					FCKStorageID: 0,
					FCKStorageCode: '',
					FRKStorageID: 0,
					FRKStorageCode: '',
					Comment: '',
					Approve: 0
				},
				posInvList: [], // 当前库位批次库存
				posInvIndex: 0,
				formDetail: [],

				PopupTabIndex: 0,
				PopupItems: ['当前批次库位', '其它批次库位', '自选库位'],
				posInvList_1: [],
				posInvList_2: [],
				posInvList_3: [],
			}
		},

		created() {

		},

		mounted() {
			let that = this;

			// 监听下拉回调
			uni.$on('BatchEditChoice', function(ret) {
				let selectItem = ret.data;

				if (ret.type == '限定出库仓库') {
					if (selectItem) {
						if (selectItem.FWarehouseID != that.formData.FCKWarehouseID) {
							that.formData.FCKWarehouseID = selectItem.FWarehouseID;
							that.formData.FCKWarehouseName = selectItem.FWarehouseName;

						}
					} else {
						that.formData.FCKWarehouseID = 0;
						that.formData.FCKWarehouseName = '';
					}
				}

				if (ret.type == '入库仓库') {
					if (selectItem) {
						if (selectItem.FWarehouseID != that.formData.FRKWarehouseID) {
							that.formData.FRKWarehouseID = selectItem.FWarehouseID;
							that.formData.FRKWarehouseName = selectItem.FWarehouseName;

							that.formData.FRKStorageID = 0;
							that.formData.FRKStorageCode = '';
						}
					} else {
						that.formData.FRKWarehouseID = 0;
						that.formData.FRKWarehouseName = '';
						that.formData.FRKStorageID = 0;
						that.formData.FRKStorageCode = '';
					}
				}

				if (ret.type == '入库库位') {
					that.formData.FRKStorageID = selectItem ? selectItem.FStorageID : 0;
					that.formData.FRKStorageCode = selectItem ? selectItem.FStorageCode : '';
				}

				if (ret.type == '子表库位') {
					let matchItem = that.formDetail[that.posRow].batchCodeArray[that.posIdx];

					if (matchItem.posid == selectItem.FStorageID && matchItem.FCKWarehouseID == matchItem
						.FRKWarehouseID) {
						that.$utils.layer.alert('出入库仓库库位不允许相同！！！');
					} else {
						matchItem.posid2 = selectItem.FStorageID;
						matchItem.posname2 = selectItem.FStorageCode;
					}

				}

				if (ret.type == '弹窗入库仓库') {
					let matchItem = that.getCurPosInvList(that.PopupTabIndex)[that.posInvIndex];
					if (selectItem.FWarehouseID != matchItem.FRKWarehouseID) {
						matchItem.FRKWarehouseID = selectItem.FWarehouseID;
						matchItem.FRKWarehouseName = selectItem.FWarehouseName;
						matchItem.FRKStorageID = 0;
						matchItem.FRKStorageCode = '';
					}

				}

				if (ret.type == '弹窗入库库位') {
					let matchItem = that.getCurPosInvList(that.PopupTabIndex)[that.posInvIndex];
					matchItem.FRKStorageID = selectItem.FStorageID;
					matchItem.FRKStorageCode = selectItem.FStorageCode;
					that.changePopupItemsValue(that.PopupTabIndex, that.checkTabHasValue(that.PopupTabIndex))
				}

				if (ret.type == '弹窗出库仓库') {
					let matchItem = that.getCurPosInvList(that.PopupTabIndex)[that.posInvIndex];
					if (selectItem.FWarehouseID != matchItem.FCKWarehouseID) {
						matchItem.FCKWarehouseID = selectItem.FWarehouseID;
						matchItem.FCKWarehouseName = selectItem.FWarehouseName;
						matchItem.FCKStorageID = 0;
						matchItem.FCKStorageCode = '';
					}
				}

				if (ret.type == '弹窗出库库位') {
					let matchItem = that.getCurPosInvList(that.PopupTabIndex)[that.posInvIndex];
					matchItem.FCKStorageID = selectItem.FStorageID;
					matchItem.FCKStorageCode = selectItem.FStorageCode;
					that.changePopupItemsValue(that.PopupTabIndex, that.checkTabHasValue(that.PopupTabIndex))

				}
			})

			// PDA扫码处理
			uni.$on('BatchEditScan', function(content) {
				let scanData = that.$utils.wmsFun.scanTransf(content);
				that.scanHandler(scanData);
			})

			// 动态计算元素高度
			that.getElementHeights();
		},

		methods: {
			clearformData(name) {
				console.log(name)
				let that = this;
				uni.showModal({
					title: '提示',
					content: `是否清除${name}？`,
					success: function(res) {
						if (res.confirm) {
							if (name == '限定出库仓库') {
								that.formData.FCKWarehouseID = 0;
								that.formData.FCKWarehouseName = '';
							} else if (name == '入库仓库') {
								that.formData.FRKWarehouseID = 0;
								that.formData.FRKWarehouseName = '';
								that.formData.FRKStorageID = 0;
								that.formData.FRKStorageCode = '';
							} else if (name == '入库库位') {
								that.formData.FRKStorageID = 0;
								that.formData.FRKStorageCode = '';
							}
						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
					}
				})
			},
			// 显示隐藏面板
			togglePanel() {
				if (this.currenTabIndex == null) {
					this.currenTabIndex = 0;
				} else {
					this.currenTabIndex = null;
				}
				this.changeTabContentHeight();
			},

			// 切换表单面板
			onClickItem(e) {
				if (this.currenTabIndex != e.currentIndex) {
					this.currenTabIndex = e.currentIndex;
					this.changeTabContentHeight();
				}
			},
			onClickPopupItem(e) {
				if (this.PopupTabIndex != e.currentIndex) {
					this.PopupTabIndex = e.currentIndex;
				}
			},

			changeTabContentHeight() {
				const query = uni.createSelectorQuery().in(this);
				this.$nextTick(() => {
					query.select('.headTabContent').boundingClientRect(rect => {
						this.headTabContentHeight = rect.height;
						console.log(this.headTabContentHeight);
						this.calcSrvHeight(this.headTabContentHeight);

					}).exec();
				})
			},

			// 获取单据详情
			getPageData() {
				let that = this;
				that.Request.request('batchCode_dbdDtl', {
						FStockID: that.formData.FStockID
					}, function(res) {
						let data = res.data;
						console.log(data);
						// 1.初始化表头信息
						that.formData.FDate = data.ds[0].FDate;
						that.formData.FCode = data.ds[0].FCode;
						that.formData.Comment = data.ds[0].Comment;
						that.formData.Approve = data.ds[0].Approve;

						// 2.初始化批次码入库明细
						var formDetail = [];
						for (var i in data.ds1) {
							var x = 0;
							for (var j in formDetail) {
								if (formDetail[j].ProductID == data.ds1[i].ProductID) {
									x = 1;
									formDetail[j].batchCodeArray.push({
										FStockDeID: data.ds1[i].FStockDeID,
										batch: data.ds1[i].FBatchNo,
										qty: data.ds1[i].FQty,
										FCKWarehouseID: data.ds1[i].FCKWarehouseID,
										FCKWarehouseName: data.ds1[i].FCKWarehouseName,
										FRKWarehouseID: data.ds1[i].FRKWarehouseID,
										FRKWarehouseName: data.ds1[i].FRKWarehouseName,
										posid: data.ds1[i].FCKStorageID,
										posname: data.ds1[i].FCKStorageCode,
										posid2: data.ds1[i].FRKStorageID,
										posname2: data.ds1[i].FRKStorageCode
									})
								}
							}

							if (x == 0) {
								formDetail.push({
									ProductID: data.ds1[i].ProductID,
									ProductCode: data.ds1[i].ProductCode,
									ProductName: data.ds1[i].ProductName,
									InventoryQty: data.ds1[i].InventoryQty,
									UnitName: data.ds1[i].UnitName,
									scannedQty: 0,
									batchCodeArray: [{
										FStockDeID: data.ds1[i].FStockDeID,
										batch: data.ds1[i].FBatchNo,
										qty: data.ds1[i].FQty,
										FCKWarehouseID: data.ds1[i].FCKWarehouseID,
										FCKWarehouseName: data.ds1[i].FCKWarehouseName,
										FRKWarehouseID: data.ds1[i].FRKWarehouseID,
										FRKWarehouseName: data.ds1[i].FRKWarehouseName,
										posid: data.ds1[i].FCKStorageID,
										posname: data.ds1[i].FCKStorageCode,
										posid2: data.ds1[i].FRKStorageID,
										posname2: data.ds1[i].FRKStorageCode
									}]
								})
							}
						}
						formDetail.forEach((row, index) => that.calcRowTotal(row, index));
						that.formDetail = formDetail;


					},
					function(err) {}, that.Request.IPAgreement() + that.Request.serverIP() +
					'/Frame/SqlData', 1)
			},

			// 保存单据
			confirmSubmit(index) {
				let that = this;

				let isEmpty = that.formDetail.every(item => item.scannedQty == 0);
				if (isEmpty) {
					that.$utils.msg('调拨明细不能为空!');
					return false;
				} else {
					let
						FProductCodes = [],
						FCKWarehouseIDs = [],
						FRKWarehouseIDs = [],
						FStorageIDs = [],
						FStorageID2s = [],
						FBatchNos = [],
						FQtys = []

					for (let i = 0; i < that.formDetail.length; i++) {
						let row = that.formDetail[i];

						for (let j = 0; j < row.batchCodeArray.length; j++) {
							let batchCode = row.batchCodeArray[j];

							FProductCodes.push(row.ProductCode);
							FCKWarehouseIDs.push(batchCode.FCKWarehouseID);
							FRKWarehouseIDs.push(batchCode.FRKWarehouseID);
							FStorageIDs.push(batchCode.posid);
							FStorageID2s.push(batchCode.posid2);
							FBatchNos.push(batchCode.batch);
							FQtys.push(batchCode.qty);
						}
					}

					let obj = {
						FStockID: that.formData.FStockID,
						Comment: that.formData.Comment,
						FCKWarehouseIDs: FCKWarehouseIDs.join(','),
						FRKWarehouseIDs: FRKWarehouseIDs.join(','),
						FProductCodes: FProductCodes.join(','),
						FStorageIDs: FStorageIDs.join(','),
						FStorageID2s: FStorageID2s.join(','),
						FBatchNos: FBatchNos.join(','),
						FQtys: FQtys.join(',')
					}

					if (index == 1) {
						that.saveFunction(obj, index);
					} else {
						uni.showModal({
							title: '提示',
							content: '是否保存当前单据',
							success: function(res) {
								if (res.confirm) {
									that.saveFunction(obj, index);
								} else if (res.cancel) {
									// console.log('用户点击取消');
								}
							}
						})
					}


				}
			},

			saveFunction(obj, index) {
				let that = this;

				that.Request.request(that.formData.FStockID == 0 ? 'batchCode_dbdAdd' :
					'batchCode_dbdEdit', obj,
					function(res) {
						let data = res.data;

						if (data.ds[0].status == 500) {
							uni.showModal({
								title: '提示',
								content: data.ds[0].msg,
								showCancel: false,
								confirmText: '确定',
								success: (res) => {
									if (res.confirm) {
										// console.log('用户点击确定');
									} else if (res.cancel) {
										// console.log('用户点击取消');
									}
								},
							});
						} else {
							if (that.formData.FStockID == 0) {
								that.formData.FStockID = data.ds[0].FStockID;
								if (index != 1) {
									that.$utils.msg('保存成功!');
								}
							} else {
								if (index != 1) {
									that.$utils.msg('修改成功!');
								}
							}
							that.getPageData();
							if (index == 1) {
								that.approveFunction();
							}
							uni.$emit('BatchListRefresh')
						}

					},
					function(err) {}, that.Request.IPAgreement() + that.Request.serverIP() +
					'/Frame/SqlData', 1)
			},

			// 单据审核
			confirmApprove() {
				let that = this;
				that.confirmSubmit(1);
			},

			// 审核单据
			approveFunction() {
				let that = this;
				let obj = {
					FStockID: that.formData.FStockID,
					isApprove: that.formData.Approve
				};

				let contentStr = '';
				if (that.formData.Approve == 0) {
					contentStr = '是否提交审核?';
				} else if (that.formData.Approve == 1) {
					contentStr = '是否取消审核?'
				}

				uni.showModal({
					title: '提示',
					content: contentStr,
					success: function(res) {
						if (res.confirm) {
							that.Request.request('batchCode_dbdApprove', obj,
								function(res) {
									let data = res.data;

									if (data.ds[0].status == 500) {
										uni.showModal({
											title: '提示',
											content: data.ds[0].msg,
											showCancel: false,
											confirmText: '确定',
											success: (res) => {
												if (res.confirm) {
													// console.log('用户点击确定');
												} else if (res.cancel) {
													// console.log('用户点击取消');
												}
											},
										});
									} else {
										if (that.formData.Approve == 0) {
											that.$utils.msg('审核成功!');
										} else {
											that.$utils.msg('取消审核成功!');
										}
										that.getPageData();
										uni.$emit('BatchListRefresh')
									}
								},
								function(err) {}, that.Request.IPAgreement() + that.Request
								.serverIP() +
								'/Frame/SqlData', 1)
						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
					}
				});
			},

			// 设置扫码物料行
			setScanRow(index) {
				this.scanRow = index;
			},

			// 删除扫码物料行
			deleteRow(row, index) {
				let that = this;
				uni.showModal({
					title: '提示',
					content: '确认删除当前行?',
					success: function(res) {
						if (res.confirm) {
							that.formDetail.splice(index, 1);
							that.$utils.msg('删除成功!');
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},

			// 删除物料批次条码
			deleteCode(row, item, index, itemIndex) {
				let that = this;
				uni.showModal({
					title: '提示',
					content: '确认删除调拨明细?',
					success: function(res) {
						if (res.confirm) {
							row.batchCodeArray.splice(itemIndex, 1);
							that.calcRowTotal(row, index);
							that.$utils.msg('删除成功!');
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},

			showChange(row, index, item, itemIndex) {
				if (!this.formData.Approve) {
					this.showChangePanel = true;
					this.isFocused = true;
					this.oldValue = item.qty;
					this.newValue = item.qty;
					this.posRow = index;
					this.posIdx = itemIndex;
				}
			},

			confirmChange() {
				var value = this.newValue;

				if (!value) {
					this.$utils.msg('数量不能为零或空!');
				} else {
					let row = this.formDetail[this.posRow];
					let item = row.batchCodeArray[this.posIdx];

					if (Number(value) != this.oldValue) {
						this.$utils.msg('数量修改成功!');
						item.qty = Number(value);
						this.calcRowTotal(row, this.posRow);
					}
				}

				this.showChangePanel = false;
				this.isFocused = false;
			},

			cancelChange() {
				this.showChangePanel = false;
				this.isFocused = false;
			},

			closeChange() {
				this.showChangePanel = false;
				this.isFocused = false;
			},
			changeInvPosition_RK(index, name) {
				console.log(index);
				this.posInvIndex = index;
				this.openBaseScreen(name);
			},
			changeInvPosition_CK(index, name) {
				console.log(index);
				if (this.PopupTabIndex != 2) {
					return;
				}
				if (this.PopupTabIndex == 2 && this.formData.FCKWarehouseID && name == '弹窗出库仓库') {
					this.$utils.msg('主表已选择限定出库仓库，不允许修改仓库!');
					return;
				}
				this.posInvIndex = index;
				this.openBaseScreen(name);
			},
			// 更改入库明细库位
			changePosition(index, itemIndex) {
				this.posRow = index;
				this.posIdx = itemIndex;
				this.openBaseScreen('子表库位');
			},

			// 计算合计扫码数量
			calcRowTotal(row, index) {
				const totalValue = row.batchCodeArray.reduce((acc, item) => acc + Number(item.qty), 0);
				row.scannedQty = totalValue;
			},

			// 打开摄像头
			openScan() {
				let that = this;
				this.$scanPopup.openScan({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success: (res) => {
						let scanData = that.$utils.wmsFun.scanTransf(res.result);
						that.scanHandler(scanData);
					}
				})

			},

			rowOpenScan() {
				this.openScan();
			},

			// 扫码处理
			scanHandler(scanData) {
				let that = this;

				if (that.scanDisabled) {
					that.$utils.msg('数据提交中,请稍后再试!');
					return false;
				}
				if (!scanData) {
					that.$utils.msg('请扫描正确的条码!');
					return false;
				}

				if (that.formData.Approve) {
					that.$utils.msg('当前单据已审核!');
					return false;
				}

				if (scanData.type == '产品批次码') {


					that.tabIndex = 1;

					that.scanDisabled = true;


					let obj = {
						ProductCode: scanData.data.code,
						FBatchNo: scanData.data.batch
					}
					that.PopupTabIndex = 0;
					that.RequestInventory(obj)

					/*
					// 批次条码匹配账面库位批次库存
					that.Request.request('batchCode_Get_Product_FBatchNo_CK_History', {
							ProductCode: scanData.data.code,
							FBatchNo: scanData.data.batch
						}, function(res) {
							that.scanDisabled = false;
							let data = res.data;
							try {
								if (data.ds.length) {
									if (data.ds[0].status == 500) {
										that.$utils.msg(data.ds[0].msg);
										return false;
									} else {
										let source = data.ds.map(item => {
											return {
												...item,
												FCKWarehouseID: item.FWarehouseID,
												FCKWarehouseName: item.FWarehouseName,
												FRKWarehouseID: that.formData.FRKWarehouseID || 0,
												FRKWarehouseName: that.formData.FRKWarehouseName || '',
												FCKStorageID: item.FStorageID,
												FCKStorageCode: item.FStorageCode,
												FRKStorageID: that.formData.FRKStorageID || 0,
												FRKStorageCode: that.formData.FRKStorageCode || '',
												ProductCode: item.ProductCode,
												FBatchNo: item.FBatchNo,
												inputQty: ''
											}
										});

										that.posInvList = source.filter((item) => {
											return (
												!that.formData.FCKWarehouseID ||
												(that.formData.FCKWarehouseID &&
													item.FCKWarehouseID == that.formData.FCKWarehouseID) ||
												item.type == 3
											)
										}) || [];

										if (that.posInvList.length) {
											that.posInvList_1 = that.posInvList.filter((item) => {
												return item.type == 1
											}) || [];

											that.posInvList_2 = that.posInvList.filter((item) => {
												return item.type == 2
											}) || [];

											that.posInvList_3 = that.posInvList.filter((item) => {
												return item.type == 3
											}) || [];

											if (that.formData.FCKWarehouseID) {
												that.posInvList_3.forEach((item) => {
													item.FCKWarehouseID = that.formData.FCKWarehouseID;
													item.FCKWarehouseName = that.formData.FCKWarehouseName;
												})
											}

											console.log(that.posInvList_1)
											console.log(that.posInvList_2)
											console.log(that.posInvList_3)
											that.PopupItems.forEach((item, index) => {
												that.changePopupItemsValue(index);
											})
											that.$refs.popupRef.open();
										} else {
											that.$utils.msg('物料库位批次库存不存在!');
											return false;
										}
									}
								} else {
									that.$utils.msg('物料库位批次库存不存在!!');
									return false;
								}
							} catch (e) {
								console.log(e);
								that.$utils.msg('物料库位批次库存不存在!');
								return false;
							}
						}, function(err) {
							that.scanDisabled = false;
						}, that.Request.IPAgreement() + that.Request.serverIP() +
						'/Frame/SqlData', 1)
					*/
				} else {
					that.$utils.msg('请扫描产品批次码！！');
				}
			},
			ViewInventory(row, index) {
				let that = this;
				that.setScanRow(index);
				let obj = {
					ProductCode: row.ProductCode
				}
				that.PopupTabIndex = 1;
				that.RequestInventory(obj)
			},
			RequestInventory(obj) {
				let that = this;
				// 批次条码匹配账面库位批次库存
				that.Request.request('batchCode_Get_Product_FBatchNo_CK_History', obj, function(res) {
						that.scanDisabled = false;
						let data = res.data;
						try {
							if (data.ds.length) {
								if (data.ds[0].status == 500) {
									that.$utils.msg(data.ds[0].msg);
									return false;
								} else {
									let source = data.ds.map(item => {
										return {
											...item,
											FCKWarehouseID: item.FWarehouseID,
											FCKWarehouseName: item.FWarehouseName,
											FRKWarehouseID: that.formData.FRKWarehouseID || 0,
											FRKWarehouseName: that.formData.FRKWarehouseName || '',
											FCKStorageID: item.FStorageID,
											FCKStorageCode: item.FStorageCode,
											FRKStorageID: that.formData.FRKStorageID || 0,
											FRKStorageCode: that.formData.FRKStorageCode || '',
											ProductCode: item.ProductCode,
											FBatchNo: item.FBatchNo,
											inputQty: ''
										}
									});

									that.posInvList = source.filter((item) => {
										return (
											!that.formData.FCKWarehouseID ||
											(that.formData.FCKWarehouseID &&
												item.FCKWarehouseID == that.formData.FCKWarehouseID) ||
											item.type == 3
										)
									}) || [];

									if (that.posInvList.length) {
										that.posInvList_1 = that.posInvList.filter((item) => {
											return item.type == 1
										}) || [];

										that.posInvList_2 = that.posInvList.filter((item) => {
											return item.type == 2
										}) || [];

										that.posInvList_3 = that.posInvList.filter((item) => {
											return item.type == 3
										}) || [];

										if (that.formData.FCKWarehouseID) {
											that.posInvList_3.forEach((item) => {
												item.FCKWarehouseID = that.formData.FCKWarehouseID;
												item.FCKWarehouseName = that.formData.FCKWarehouseName;
											})
										}

										console.log(that.posInvList_1)
										console.log(that.posInvList_2)
										console.log(that.posInvList_3)
										that.PopupItems.forEach((item, index) => {
											that.changePopupItemsValue(index);
										})
										that.$refs.popupRef.open();
									} else {
										that.$utils.msg('物料库位批次库存不存在!');
										return false;
									}
								}
							} else {
								that.$utils.msg('物料库位批次库存不存在!!');
								return false;
							}
						} catch (e) {
							console.log(e);
							that.$utils.msg('物料库位批次库存不存在!');
							return false;
						}
					}, function(err) {
						that.scanDisabled = false;
					}, that.Request.IPAgreement() + that.Request.serverIP() +
					'/Frame/SqlData', 1)
			},
			getCurPosInvList(type) {
				let that = this;
				console.log(type)
				console.log(that[`posInvList_${type+1}`])
				return that[`posInvList_${type+1}`];
			},
			// 获取相关元素高度
			getElementHeights() {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					const promises = [];
					// 获取每个元素的高度，并返回一个 Promise
					const getHeightPromise = (selector) => {
						return new Promise((resolve) => {
							query.select(selector).boundingClientRect((rect) => {
								resolve(rect.height);
							}).exec();
						});
					};

					promises.push(getHeightPromise('.headTabWrap'));
					promises.push(getHeightPromise('.headTabContent'));
					promises.push(getHeightPromise('.detail-label'));
					promises.push(getHeightPromise('.bottom'));

					// 等待所有 Promise 完成
					Promise.all(promises).then((heights) => {
						console.log(heights);
						this.headTabWrapHeight = heights[0];
						this.headTabContentHeight = heights[1];
						this.detailLabelHeight = heights[2];
						this.bottomHeight = heights[3];

						this.calcSrvHeight(this.headTabContentHeight);
					});
				})
			},

			// 重新计算scrollview高度
			calcSrvHeight(headTabContentHeight) {
				let safeAreaTop = this.$u.sys().statusBarHeight;
				let height =
					`calc(100vh - 44px - ${safeAreaTop}px - ${this.headTabWrapHeight}px - ${headTabContentHeight}px - ${this.detailLabelHeight}px - ${this.bottomHeight}px)`;
				this.srvHeight = height;
				console.log(this.srvHeight);
			},

			// 公共下拉选择
			openBaseScreen(str) {
				let url = '/commonPage/Tool/baseScreen';
				let obj;

				if (str == '限定出库仓库') {
					obj = {
						allowClear: true,
						cmd: 'Droplist_Warehouse',
						type: str,
						ListeningName: 'BatchEditChoice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							showText: 'FWarehouseName', //查询结果显示的字段
							ChoiceDataKey: 'FWarehouseID',
							ChoiceDataData: this.formData.FCKWarehouseID
						},
						param: {

						}
					}
				}

				if (str == '入库仓库') {
					obj = {
						allowClear: true,
						cmd: 'Droplist_Warehouse',
						type: str,
						ListeningName: 'BatchEditChoice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							showText: 'FWarehouseName', //查询结果显示的字段
							ChoiceDataKey: 'FWarehouseID',
							ChoiceDataData: this.formData.FRKWarehouseID
						},
						param: {

						}
					}
				}

				if (str == '入库库位') {
					if (!this.formData.FRKWarehouseID) {
						this.$utils.msg('请先选择入库仓库!');
						return false;
					}

					obj = {
						allowClear: true,
						cmd: 'Droplist_Storage',
						type: str,
						ListeningName: 'BatchEditChoice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							searchKey: 'FStorageCode',
							showText: 'FStorageCode', //查询结果显示的字段
							ChoiceDataKey: 'FStorageID',
							ChoiceDataData: this.formData.FRKStorageID
						},
						param: {
							FWarehouseID: this.formData.FRKWarehouseID
						}
					}
				}

				if (str == '子表库位') {
					obj = {
						allowClear: false,
						cmd: 'Droplist_Storage',
						type: str,
						ListeningName: 'BatchEditChoice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							searchKey: 'FStorageCode',
							showText: 'FStorageCode', //查询结果显示的字段
							ChoiceDataKey: 'FStorageID',
							ChoiceDataData: this.formDetail[this.posRow].batchCodeArray[this.posIdx].posid2
						},
						param: {
							FWarehouseID: this.formDetail[this.posRow].batchCodeArray[this.posIdx].FRKWarehouseID
						}
					}
				}

				if (str == '弹窗入库仓库') {
					let match_posInvList = this.getCurPosInvList(this.PopupTabIndex)[this.posInvIndex]
					obj = {
						allowClear: false,
						cmd: 'Droplist_Warehouse',
						type: str,
						ListeningName: 'BatchEditChoice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							showText: 'FWarehouseName', //查询结果显示的字段
							ChoiceDataKey: 'FWarehouseID',
							ChoiceDataData: match_posInvList.FRKWarehouseID
						},
						param: {

						}
					}
				}

				if (str == '弹窗入库库位') {
					let match_posInvList = this.getCurPosInvList(this.PopupTabIndex)[this.posInvIndex]
					if (!match_posInvList.FRKWarehouseID) {
						this.$utils.msg('请先选择入库仓库!');
						return false;
					}

					obj = {
						allowClear: false,
						cmd: 'Droplist_Storage',
						type: str,
						ListeningName: 'BatchEditChoice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							searchKey: 'FStorageCode',
							showText: 'FStorageCode', //查询结果显示的字段
							ChoiceDataKey: 'FStorageID',
							ChoiceDataData: match_posInvList.FRKStorageID
						},
						param: {
							FWarehouseID: match_posInvList.FRKWarehouseID
						}
					}
				}

				if (str == '弹窗出库仓库') {
					let match_posInvList = this.getCurPosInvList(this.PopupTabIndex)[this.posInvIndex]
					obj = {
						allowClear: false,
						cmd: 'Droplist_Warehouse',
						type: str,
						ListeningName: 'BatchEditChoice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							showText: 'FWarehouseName', //查询结果显示的字段
							ChoiceDataKey: 'FWarehouseID',
							ChoiceDataData: match_posInvList.FCKWarehouseID
						},
						param: {

						}
					}
				}

				if (str == '弹窗出库库位') {
					let match_posInvList = this.getCurPosInvList(this.PopupTabIndex)[this.posInvIndex]

					if (!match_posInvList.FCKWarehouseID) {
						this.$utils.msg('请先选择出库仓库!');
						return false;
					}

					obj = {
						allowClear: false,
						cmd: 'Droplist_Storage',
						type: str,
						ListeningName: 'BatchEditChoice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							searchKey: 'FStorageCode',
							showText: 'FStorageCode', //查询结果显示的字段
							ChoiceDataKey: 'FStorageID',
							ChoiceDataData: match_posInvList.FCKStorageID
						},
						param: {
							FWarehouseID: match_posInvList.FCKWarehouseID
						}
					}
				}

				this.$store.commit('ChangeAndSetStateData', {
					Name1: 'BaseScreenParm',
					data: obj
				})

				uni.navigateTo({
					url: url
				})
			},
			validateItem(item) {
				let that = this;
				const qty = parseFloat(item.inputQty);
				const stock = parseFloat(item.FQty);
				if (qty <= 0) {
					that.$utils.msg('出库数量必须大于 0');
					item.inputQty = '';
					return false;
				}
				// if (qty > stock) {
				// 	that.$utils.msg('不能超过库存');
				// 	item.inputQty = '';
				// 	return false;
				// }
				if ((!item.FCKStorageCode || !item.FRKStorageCode) && qty) {
					that.$utils.msg('存在已填写数量但未选择库位的明细！！');
					return false;
				}

				that.changePopupItemsValue(that.PopupTabIndex, that.checkTabHasValue(that.PopupTabIndex))
				return true;
			},
			// 库位批次库存-选择
			confirmInvSel() {
				let that = this;
				let selectedItem = that.posInvList.filter((item) => {
					return item.inputQty > 0 && (item.FCKStorageCode && item.FRKStorageCode)
				})
				console.log(selectedItem)
				//1、出入库仓库库位不允许相同
				let WhetherSame = selectedItem.some((item) => {
					return item.FRKWarehouseID == item.FCKWarehouseID && item.FRKStorageID == item
						.FCKStorageID
				})
				if (WhetherSame) {
					that.$utils.msg('出入库仓库库位不允许相同！！！');
					return false;
				}

				if (selectedItem.length) {
					let list = selectedItem.map(item => {
						return {
							...item,
							FStockDeID: 0,
							FQty: Number(item.inputQty),
							batch: item.FBatchNo,
							qty: Number(item.inputQty),
							posid: item.FCKStorageID,
							posname: item.FCKStorageCode,
							posid2: item.FRKStorageID,
							posname2: item.FRKStorageCode
						}
					})

					// 当前选中物料行
					var matchRow;
					var matchIndex;


					let flag = that.formDetail.some(item => item.ProductCode == list[0].ProductCode);

					// 新增物料扫码行
					if (!flag) {
						that.formDetail.push({
							ProductID: list[0].ProductID,
							ProductCode: list[0].ProductCode,
							ProductName: list[0].ProductName,
							InventoryQty: list[0].InventoryQty,
							UnitID: list[0].UnitID,
							UnitName: list[0].UnitName,
							scannedQty: 0,
							batchCodeArray: []
						})
						matchRow = that.formDetail[that.formDetail.length - 1];
						matchIndex = that.formDetail.length - 1;
					} else {
						matchRow = that.formDetail.find(item => item.ProductCode == list[0].ProductCode);
						matchIndex = that.formDetail.findIndex(item => item.ProductCode == list[0].ProductCode);
					}

					matchRow.batchCodeArray = [...list, ...matchRow.batchCodeArray];
					that.setScanRow(matchIndex);
					that.calcRowTotal(matchRow, matchIndex);


					that.$refs.popupRef.close();

				} else {
					that.$utils.msg('数量和库位不能为空！！！');
				}
			},
			// 库位批次库存-取消
			cancelInvSel() {
				this.$refs.popupRef.close();
			},
			put_Qty(item) {
				let that = this;
				item.inputQty = Number(item.FQty)
				that.validateItem(item);
			},
			checkTabHasValue(index) {
				let that = this;
				let flag = false;
				try {
					flag = that.getCurPosInvList(index).some((item) => {
						return item.inputQty > 0 && (item.FCKStorageCode && item.FRKStorageCode)
					});
				} catch (e) {
					console.log(e);
					flag = false;
				}
				console.log(flag)

				return flag
			},
			changePopupItemsValue(index, hasValue = false) {
				let arr = ['当前批次库位', '其它批次库位', '自选库位'];
				let str = '☑';
				let value = hasValue ? `${str}${arr[index]}` : arr[index];

				this.$set(this.PopupItems, index, value);
			},
		},


		onLoad(option) {
			let menuName = decodeURIComponent(option.menuName);
			this.titleName = menuName + '详情';
			this.formData.FStockID = parseInt(option.FStockID);

			if (this.formData.FStockID != 0) {
				this.getPageData();
			} else {
				this.formData.FDate = this.$utils.dateFormat(new Date(), 'Y-MM-dd');
			}
		},

		onUnload() {
			uni.$off('BatchEditChoice');
			uni.$off('BatchEditScan');
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/static/assets/scss/wms.scss";

	.del-content,
	.del-title {
		width: 12%;
	}

	.batch-title,
	.batch-content {
		flex: 1;
		min-width: 24%;
	}

	.qty-title,
	.qty-content {
		width: 20%;
	}

	.pos-title,
	.pos-content {
		width: 20%;
	}

	.form1 .item-label {
		width: 120px;
	}
</style>